import http.server as hs
import sys, os
import cgi
import json

class RequestHandler(hs.BaseHTTPRequestHandler):
    def send_content(self, page, status = 200):
        self.send_response(status)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-Length", str(len(page)))
        self.end_headers()
        self.wfile.write(bytes(page, encoding = 'utf-8'))
    def do_POST(self): 
        try:
            #获取文件路径
            # full_path = os.getcwd() + self.path
            ctype, pdict = cgi.parse_header(self.headers['content-type'])
            if ctype == 'multipart/form-data':
                postvars = cgi.parse_multipart(self.rfile, pdict)
            elif ctype == 'application/x-www-form-urlencoded':
                length = int(self.headers['content-length'])
                postvars = cgi.parse(self.rfile.read(length), keep_blank_values=1)
            elif ctype=='application/json':
                length = int(self.headers['content-length'])
                byte=self.rfile.read(length)
                rjson=json.loads(byte.decode())
                WebService.cb(rjson,self.client_address)
            else:
                postvars = {}
            self.send_content(ctype,200)
        except Exception as msg:
            self.send_content("出错"+str(msg), 500)
            WebService.log_callBack(msg,1)

class WebService:
    cb=None
    def __init__(self,port,callBack,log_callBack):
        WebService.cb=callBack
        WebService.log_callBack=log_callBack
        hs.HTTPServer(('0.0.0.0', port), RequestHandler).serve_forever()